import os

from fastapi import APIRouter, Depends, Request, UploadFile, File
from fastapi import Form

from api.router.model.user_model import User
from api.src.cache.key import remove_bg_queue
from config import appSettings
from service.api_service.users import UsersService
from ..dependencies import get_current_user, get_token_header
from service.api_service.ai import AIService

ai_service = AIService(
    appSettings.rem_model_path,
    appSettings.picture_input_path,
    appSettings.picture_save_path,
)
user_service = UsersService()
router = APIRouter(
    prefix="/ai",
    tags=["AI"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)


@router.post(
    "/ai_modnet_v2",
    tags=["custom"],
    responses={403: {"description": "Operation forbidden"}},
)
async def ai_modnet_v2(file: UploadFile):
    # 检测是否有效用户
    return await ai_modnet_v2(file)


@router.post(
    "/ai_replace_bg",
    tags=["custom"],
    responses={403: {"description": "Operation forbidden"}},
)
async def ai_replace_bg(
    request: Request,
    user: User = Depends(get_current_user),
    file: UploadFile = File(...),
    size: str = Form(...),
    pixel: str = Form(...),
):
    # 图片存储
    # 保存文件保存到服务器
    print(file.filename)
    file_path = os.path.join(appSettings.picture_input_path, file.filename)
    with open(file_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)
    # 创建订单
    order = user_service.create_order(
        user.user_id, file_path, size=size, pixel=pixel, type=1
    )
    # 消息写入队列 异步处理 前端轮训获取处理进度
    push_msg = f'{{"order_id":{order.id},"user_id":{user.user_id},"image":"{file_path}","size":"{size}","pexil":"{pixel}","type":1}}'
    await request.app.state.redis.lpush(remove_bg_queue(), push_msg)
    print(push_msg)
    # res = ai_service.remove_bg(appSettings.picture_input_path + f"/{file.filename}")
    return {"code": 0, "message": "File uploaded successfully", "data": order}
